<template>
  <div v-if="visible" class="modal-overlay" @click="handleClose">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>{{ isEdit ? '编辑交易' : '添加交易' }}</h3>
        <button class="close-button" @click="handleClose">×</button>
      </div>

      <form @submit.prevent="handleSubmit" class="transaction-form">
        <div class="form-grid">
          <!-- 交易类型 -->
          <div class="form-group">
            <label for="transaction_type">交易类型 *</label>
            <el-select
              id="transaction_type"
              v-model="formData.transaction_type"
              required
              placeholder="请选择交易类型"
              @change="handleTypeChange"
              style="width: 100%"
            >
              <el-option label="收入" value="income" />
              <el-option label="支出" value="expense" />
            </el-select>
          </div>

          <!-- 金额 -->
          <div class="form-group">
            <label for="amount">金额 *</label>
            <el-input-number
              id="amount"
              v-model="formData.amount"
              :precision="2"
              :min="0.01"
              :step="0.01"
              required
              placeholder="0.00"
              style="width: 100%"
            />
          </div>

          <!-- 交易日期 -->
          <div class="form-group">
            <label for="transaction_date">交易日期 *</label>
            <el-date-picker
              id="transaction_date"
              v-model="formData.transaction_date"
              type="date"
              required
              placeholder="选择交易日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </div>

          <!-- 账户 -->
          <div class="form-group">
            <label for="account_id">账户 *</label>
            <el-select
              id="account_id"
              v-model="formData.account_id"
              required
              placeholder="请选择账户"
              @change="handleAccountChange"
              style="width: 100%"
            >
              <el-option
                v-for="account in accounts"
                :key="account.id"
                :label="`${account.name} (¥${formatAmount(parseFloat(account.balance))})`"
                :value="account.id"
              />
              <el-option label="+ 新增账户" value="add_new" class="add-new-option" />
            </el-select>
          </div>

          <!-- 分类 -->
          <div class="form-group">
            <label for="category_id">分类</label>
            <el-select
                id="category_id"
                v-model="formData.category_id"
                placeholder="请选择分类"
                @change="handleCategoryChange"
                style="width: 100%"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
                <el-option label="+ 新增分类" value="add_new" class="add-new-option" />
              </el-select>
          </div>

          <!-- 项目 -->
          <div class="form-group">
            <label for="project_id">项目</label>
            <el-select
              id="project_id"
              v-model="formData.project_id"
              placeholder="请选择项目"
              @change="handleProjectChange"
              style="width: 100%"
            >
              <el-option
                v-for="project in projects"
                :key="project.id"
                :label="project.name"
                :value="project.id"
              />
              <el-option label="+ 新增项目" value="add_new" class="add-new-option" />
            </el-select>
          </div>

          <!-- 描述 -->
          <div class="form-group full-width">
            <label for="description">描述</label>
            <el-input
              id="description"
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入交易描述..."
              style="width: 100%"
            />
          </div>

          <!-- 标签 -->
          <div class="form-group full-width">
            <label for="tags">标签</label>
            <el-input
              id="tags"
              v-model="formData.tags"
              placeholder="用逗号分隔多个标签"
              style="width: 100%"
            />
          </div>
        </div>

        <div class="form-actions">
          <button type="button" class="btn-cancel" @click="handleClose">
            取消
          </button>
          <button type="submit" class="btn-primary" :disabled="loading">
            {{ loading ? (isEdit ? "更新中..." : "创建中...") : (isEdit ? "更新交易" : "创建交易") }}
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- 分类管理弹窗 -->
  <CategoryManagementModal
    v-model:visible="showCategoryManagement"
    @close="closeCategoryManagement"
    @success="handleCategoryManagementSuccess"
  />

  <!-- 账户管理弹窗 -->
  <AccountManagementModal
    v-model:visible="showAccountManagement"
    @close="closeAccountManagement"
    @success="handleAccountManagementSuccess"
  />

  <!-- 项目管理弹窗 -->
  <ProjectManagementModal
    v-model:visible="showProjectManagement"
    @close="closeProjectManagement"
    @success="handleProjectManagementSuccess"
  />
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted, onUnmounted } from "vue";
import { useAccountingStore } from "@/stores/accounting";
import { getCurrentDate } from "@/utils/dateUtils";
import type { TransactionCreate, TransactionType, TransactionResponse } from "@/types/accounting";
import CategoryManagementModal from "./CategoryManagementModal.vue";
import AccountManagementModal from "./AccountManagementModal.vue";
import ProjectManagementModal from "./ProjectManagementModal.vue";

interface Props {
  visible: boolean;
  editData?: TransactionResponse | null;
}

interface Emits {
  (e: "update:visible", visible: boolean): void;
  (e: "close"): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const accountingStore = useAccountingStore();

// 编辑模式状态
const isEdit = computed(() => props.editData && props.editData.id);

// 获取数据
const accounts = computed(() => accountingStore.accounts);
const categories = computed(() => accountingStore.categories);
const projects = computed(() => accountingStore.projects);

// 确保数据在组件挂载时加载
onMounted(async () => {
  if (props.visible) {
    await loadData();
  }
});

// 表单数据
const formData = reactive<{
  transaction_type: TransactionType;
  amount: string;
  transaction_date: string;
  account_id: number | string;
  category_id: number | string | null;
  project_id: number | string | null;
  description: string | null;
  is_recurring: boolean;
  recurring_pattern: string | null;
  tags: string | null;
  to_account_id: number | null;
  member_id: number | null;
  receipt_image: string | null;
}>({
  transaction_type: "expense" as TransactionType,
  amount: "",
  transaction_date: getCurrentDate(),
  account_id: 0,
  category_id: null,
  project_id: null,
  description: null,
  is_recurring: false,
  recurring_pattern: null,
  tags: null,
  to_account_id: null,
  member_id: null,
  receipt_image: null,
});

// 加载状态
const loading = ref(false);

// 管理弹窗状态
const showCategoryManagement = ref(false);
const showAccountManagement = ref(false);
const showProjectManagement = ref(false);

// 弹窗层级管理
const modalStack = ref<string[]>([]);

// 添加弹窗到栈
const pushModal = (modalName: string) => {
  modalStack.value.push(modalName);
};

// 从栈中移除弹窗
const popModal = () => {
  return modalStack.value.pop();
};

// 获取最顶层弹窗
const getTopModal = () => {
  return modalStack.value[modalStack.value.length - 1];
};

// 关闭最顶层弹窗
const closeTopModal = () => {
  const topModal = getTopModal();
  if (topModal) {
    switch (topModal) {
      case 'category':
        closeCategoryManagement();
        break;
      case 'account':
        closeAccountManagement();
        break;
      case 'project':
        closeProjectManagement();
        break;
    }
  }
};

// 处理键盘事件
const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === "Escape") {
    closeTopModal();
  }
};

// 在组件挂载时添加键盘事件监听器
onMounted(() => {
  document.addEventListener('keydown', handleKeyDown);
});

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown);
});

// 监听visible变化，重置表单和获取数据
watch(
  () => props.visible,
  async (newVisible) => {
    if (newVisible) {
      resetForm();
      await loadData();
    }
  },
);

// 加载必要的数据
async function loadData() {
  try {
    await Promise.all([
      accountingStore.fetchCategories(),
      accountingStore.fetchAccounts(),
      accountingStore.fetchProjects(),
    ]);
  } catch (error) {
    console.error("加载数据失败:", error);
  }
}

// 重置表单
function resetForm() {
  if (props.editData) {
    // 编辑模式：填充现有数据
    formData.transaction_type = props.editData.transaction_type;
    formData.amount = props.editData.amount;
    formData.transaction_date = props.editData.transaction_date;
    formData.account_id = props.editData.account_id;
    formData.category_id = props.editData.category_id ?? null;
    formData.project_id = props.editData.project_id ?? null;
    formData.description = props.editData.description ?? null;
    formData.is_recurring = props.editData.is_recurring || false;
    formData.recurring_pattern = props.editData.recurring_pattern ?? null;
    formData.tags = props.editData.tags ?? null;
    formData.to_account_id = props.editData.to_account_id ?? null;
    formData.member_id = props.editData.member_id ?? null;
    formData.receipt_image = props.editData.receipt_image ?? null;
  } else {
    // 添加模式：清空表单
    formData.transaction_type = "expense" as TransactionType;
    formData.amount = "";
    formData.transaction_date = getCurrentDate();
    formData.account_id = 0;
    formData.category_id = null;
    formData.project_id = null;
    formData.description = null;
    formData.is_recurring = false;
    formData.recurring_pattern = null;
    formData.tags = null;
    formData.to_account_id = null;
    formData.member_id = null;
    formData.receipt_image = null;
  }
}

// 处理类型变化
function handleTypeChange() {
  // 可以在这里添加类型变化时的逻辑
}

// 处理账户变化
function handleAccountChange() {
  if (formData.account_id === "add_new") {
    openAccountManagement();
    // 重置选择
    formData.account_id = 0;
  }
}

// 处理分类变化
function handleCategoryChange() {
  if (formData.category_id === "add_new") {
    openCategoryManagement();
    // 重置选择
    formData.category_id = null;
  }
}

// 处理项目变化
function handleProjectChange() {
  if (formData.project_id === "add_new") {
    openProjectManagement();
    // 重置选择
    formData.project_id = null;
  }
}


// 格式化金额
function formatAmount(amount: number): string {
  return amount.toFixed(2);
}

// 处理关闭
function handleClose() {
  emit("update:visible", false);
  emit("close");
}

// 处理提交
async function handleSubmit() {
  if (
    !formData.transaction_type ||
    !formData.amount ||
    !formData.transaction_date ||
    !formData.account_id ||
    formData.account_id === "add_new" ||
    typeof formData.account_id === "string"
  ) {
    alert("请填写所有必填字段");
    return;
  }

  try {
    loading.value = true;

    // 验证金额
    const amount = parseFloat(formData.amount);
    if (isNaN(amount) || amount <= 0) {
      alert("请输入有效的金额");
      return;
    }

    // 准备提交数据
    const submitData: TransactionCreate = {
      transaction_type: formData.transaction_type,
      amount: formData.amount,
      transaction_date: formData.transaction_date,
      account_id: typeof formData.account_id === "number" ? formData.account_id : 0,
      category_id: formData.category_id && typeof formData.category_id === "number" ? formData.category_id : null,
      project_id: formData.project_id && typeof formData.project_id === "number" ? formData.project_id : null,
      description: formData.description || null,
      is_recurring: formData.is_recurring || false,
      recurring_pattern: formData.recurring_pattern || null,
      tags: formData.tags || null,
      to_account_id: null,
      member_id: null,
      receipt_image: null,
    };

    if (isEdit.value && props.editData) {
      // 编辑模式：更新交易
      await accountingStore.updateTransaction(props.editData.id, submitData);
    } else {
      // 添加模式：创建交易
      await accountingStore.createTransaction(submitData);
    }

    // 成功后关闭模态框
    emit("success");
    emit("close");
  } catch (error) {
    console.error(isEdit.value ? "更新交易失败:" : "创建交易失败:", error);
    alert(isEdit.value ? "更新交易失败，请重试" : "创建交易失败，请重试");
  } finally {
    loading.value = false;
  }
}


// 打开分类管理
const openCategoryManagement = () => {
  showCategoryManagement.value = true;
  pushModal('category');
};

// 关闭分类管理
const closeCategoryManagement = () => {
  showCategoryManagement.value = false;
  popModal();
};

// 分类管理成功
const handleCategoryManagementSuccess = () => {
  closeCategoryManagement();
  // 分类数据会自动更新，因为使用的是store的数据
};

// 打开账户管理
const openAccountManagement = () => {
  showAccountManagement.value = true;
  pushModal('account');
};

// 关闭账户管理
const closeAccountManagement = () => {
  showAccountManagement.value = false;
  popModal();
};

// 账户管理成功
const handleAccountManagementSuccess = () => {
  closeAccountManagement();
  // 账户数据会自动更新，因为使用的是store的数据
};

// 打开项目管理
const openProjectManagement = () => {
  showProjectManagement.value = true;
  pushModal('project');
};

// 关闭项目管理
const closeProjectManagement = () => {
  showProjectManagement.value = false;
  popModal();
};

// 项目管理成功
const handleProjectManagementSuccess = () => {
  closeProjectManagement();
  // 项目数据会自动更新，因为使用的是store的数据
};
</script>

<style lang="scss" scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(5px);
}

// Enhanced dropdown styling
:deep(.el-select) {
  .el-input__wrapper {
    border-radius: var(--el-border-radius-small);
    transition: all 0.3s ease;
    
    &:hover {
      border-color: var(--el-border-color-light);
    }
    
    &.is-focus {
      border-color: var(--el-color-primary);
      box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
    }
  }
  
  .el-input__inner {
    font-size: 14px;
    color: var(--el-text-color-primary);
  }
}

:deep(.el-select-dropdown) {
  border-radius: var(--el-border-radius-base);
  border: 1px solid var(--el-border-color);
  box-shadow: var(--el-box-shadow-light);
  
  .el-select-dropdown__item {
    font-size: 14px;
    padding: 8px 16px;
    transition: all 0.2s ease;
    
    &:hover {
      background: var(--el-bg-color-overlay);
      color: var(--el-color-primary);
    }
    
    &.selected {
      color: var(--el-color-primary);
      font-weight: 500;
    }
    
    &.add-new-option {
      color: var(--el-color-success);
      font-weight: 500;
      
      &:hover {
        background: rgba(var(--el-color-success-rgb), 0.1);
      }
    }
  }
}

.modal-content {
  background: var(--el-bg-color);
  border-radius: var(--el-border-radius-base);
  box-shadow: var(--el-box-shadow-light);
  width: 95%;
  max-width: 800px;
  max-height: 85vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  border: 1px solid var(--el-border-color);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color);

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  }
}

.close-button {
  background: none;
  border: none;
  font-size: 20px;
  color: var(--el-text-color-secondary);
  cursor: pointer;
  padding: 4px;
  border-radius: var(--el-border-radius-small);
  transition: all 0.3s ease;

  &:hover {
    background: rgba(0, 0, 0, 0.1);
    color: var(--el-text-color-primary);
  }
}

.transaction-form {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;

  .full-width {
    grid-column: 1 / -1;
  }
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;

  label {
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  }

  }

input[type="text"],
input[type="number"],
input[type="date"],
select,
textarea {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-small);
  font-size: 14px;
  padding: 8px 16px;
  outline: none;
  transition: all 0.3s ease;

  &:focus {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

textarea {
  resize: vertical;
  min-height: 80px;
}


.form-actions {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  margin-top: 20px;

  button {
    flex: 1;
    padding: 12px 20px;
    border: none;
    border-radius: var(--el-border-radius-small);
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
}

.btn-cancel {
  background: var(--el-bg-color);
  color: var(--el-text-color-secondary);
  border: 1px solid var(--el-border-color);

  &:hover:not(:disabled) {
    background: var(--el-bg-color-overlay);
    color: var(--el-text-color-primary);
  }
}

.btn-primary {
  background: var(--el-color-primary);
  color: white;

  &:hover:not(:disabled) {
    background: var(--el-color-primary-light-3);
    transform: translateY(-1px);
  }
}

@media (max-width: 768px) {
  .modal-content {
    width: 98%;
    max-width: none;
    max-height: 90vh;
    border-radius: var(--el-border-radius-small);
  }

  .modal-header {
    padding: 16px;
    
    h3 {
      font-size: 16px;
    }
  }

  .transaction-form {
    padding: 16px;
  }

  .form-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .form-actions {
    flex-direction: column;
    gap: 12px;
  }

  .form-group {
    label {
      font-size: 13px;
    }
  }
}

@media (max-width: 480px) {
  .modal-content {
    width: 100%;
    height: 100vh;
    max-height: 100vh;
    border-radius: 0;
  }

  .modal-header {
    padding: 12px;
    
    h3 {
      font-size: 14px;
    }
  }

  .transaction-form {
    padding: 12px;
  }

  .form-grid {
    gap: 8px;
  }

  .form-actions {
    padding: 0 12px 12px 12px;
  }
}

@media (max-height: 600px) {
  .modal-content {
    max-height: 95vh;
  }
  
  .modal-header {
    padding: 12px 16px;
  }
  
  .transaction-form {
    padding: 12px 16px;
  }
}
</style>
